package com.xyy.saas.payment.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.JSONUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wangtianqi
 * @date 2020/5/7 14:59
 */
@Component
@DependsOn("apolloUtil")
public class BusinessTypeConfig implements InitializingBean {

    private static final String BUSINESS_TYPE_MAP = "business.type.map";

    private static final String BUSINESS_TYPE = "businessType";

    private static final String BUSINESS_ID_TYPE = "businessIdType";

    private static final String BUSINESS_ORDER_TYPE = "businessOrderType";

    private Map<String, String> configMap = JSONUtils.parse2Map(ApolloUtil.getProperty(BUSINESS_TYPE_MAP), String.class, String.class);

    private List<String> businessTypeList;
    private List<String> businessIdTypeList;
    private List<String> businessOrderTypeList;

    private void initConfig() {
        businessTypeList = JSONUtils.parse2List(configMap.get(BUSINESS_TYPE), String.class);
        businessIdTypeList = JSONUtils.parse2List(configMap.get(BUSINESS_ID_TYPE), String.class);
        businessOrderTypeList = JSONUtils.parse2List(configMap.get(BUSINESS_ORDER_TYPE), String.class);
    }


    public boolean checkBusinessType(String businessType) {
        return businessTypeList.contains(businessType);
    }

    public boolean checkBusinessIdType(String businessIdType) {
        return businessIdTypeList.contains(businessIdType);
    }

    public boolean checkBusinessOrderType(String businessOrderType) {
        return businessOrderTypeList.contains(businessOrderType);
    }

    public boolean checkAllType(String businessType, String businessIdType, String businessOrderType) {
        return checkBusinessType(businessType) && checkBusinessIdType(businessIdType) && checkBusinessOrderType(businessOrderType);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        initConfig();
        Set set = new HashSet();
        set.add(BUSINESS_TYPE_MAP);
        //动态监听配置变化
        Config config = ConfigService.getAppConfig();
        config.addChangeListener(new ConfigChangeListener() {
            @Override
            public void onChange(ConfigChangeEvent changeEvent) {
                configMap = JSONUtils.parse2Map(ApolloUtil.getProperty(BUSINESS_TYPE_MAP), String.class, String.class);
                initConfig();
            }
        }, set);
    }
}
